<%@page import="java.net.URL"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="net.sf.json.JSONObject"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%!
public class HttpUtil{
	public JSONObject getSimpleHttpresult(String url,String params){
		try {
			URL url1 = new URL(url+(params==null?"":params));
			HttpURLConnection conn = (HttpURLConnection)url1.openConnection();
	        conn.setRequestProperty("contentType", "UTF-8");
	        conn.setRequestMethod("POST");
	        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
	        
	        conn.setConnectTimeout(120 * 1000);
	        InputStream inStream =  conn.getInputStream();  //通过输入流获取html二进制数据
	        String htmlSource = readInputStream(inStream); 
	        inStream.close();
	        System.out.println(htmlSource);
	        return JSONObject.fromObject(htmlSource);

		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject obj = new JSONObject();
		obj.put("code", -1);
		return obj;
	}
	public String readInputStream(InputStream instream) throws Exception {
		InputStreamReader reader = new InputStreamReader(instream,"UTF-8");
		BufferedReader br = new BufferedReader(reader);
		StringBuffer sb = new StringBuffer();
		String data = br.readLine();
		while (data!=null) {
			sb.append(data+"\n");
			data = br.readLine();
		} 
		return sb.toString();
    }
};
%>
<%
String code = request.getParameter("code");
String state = request.getParameter("state");
HttpUtil http = new HttpUtil();
String appid = "wx747ca4a419a0a9fc";
String appsecret = "eb01075b61db4b0bc21ec9184f181302";
String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",appid,appsecret,code);
//out.println(url);
JSONObject result = http.getSimpleHttpresult(url, "");
//out.println(result.toString());
if(result.get("code")!=null&&result.getInt("code")==-1){
	out.println("get userinfo from weixin error .");
	return;
}
String openid = result.get("openid");
String nickname = result.get("nickname");
String sex = result.get("sex");
String province = result.get("province");
String city = result.get("city");
String headimgurl = result.get("headimgurl");
String returnUrl = "https://www.baidu.com";
if(state.equals("url")){
	returnUrl = "http://mp.gene1987.com/wx/htmls/pcenter.html";
}
String param = String.format("nickname=%s&openid=%s&sex=%s&city=%s&province=%s&userimg=%s", nickname,openid,sex,city,province,headimgurl);
response.sendRedirect(returnUrl+"?"+param);
%>

